package today.rocky.boot.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author Rocky
 * @version 1.0
 * @date 2020/5/13 9:38
 * EnableWebSecurity启用security
 * EnableGlobalMethodSecurity(prePostEnabled = true) 启用方法拦截，会拦截@PreAuthrize注解配置
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	/**
	 * 基于内存构建
	 * admin/123456  user/123456
	 * @param auth
	 * @throws Exception
	 */
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.inMemoryAuthentication()
				.passwordEncoder(new BCryptPasswordEncoder())
				.withUser("admin")
				.password(new BCryptPasswordEncoder().encode("123456"))
				.roles("admin");
		//这样写会报错，必须加密
		//auth.inMemoryAuthentication().withUser("user").password("123456").roles();
		//上面没改，下面是通过注入bean配置加密
		auth.inMemoryAuthentication()
				.withUser("user")
				.password("123456")
				.roles("user");
	}

	@Bean
	public PasswordEncoder passwordEncoder(){
		return new BCryptPasswordEncoder();
	}
}
